package com.xiaotu.impRunnable;

/**
 * @Author xiaotu
 * @Description //TODO
 * @Date 2022/3/24 17:31
 * @ClassName Race
 * @Version 1.0
 * 模拟龟兔赛跑
 **/
public class Race implements Runnable{
    public static String winner;
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            synchronized (Race.class) {
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (gameOver(i)) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
            }
        }
    }
    //判断是否完成了比赛
    public boolean gameOver(int steps){
        //判断是否有了胜利者
        if(winner!=null){
            return true;
        }else{
            if(steps>=100){
                winner = Thread.currentThread().getName();
                System.out.println("winner is "+ winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();
        Thread t1 = new Thread(race,"兔子");
        Thread t2 = new Thread(race,"乌龟");
        t1.start();
        t2.start();
    }
}
